package com.solver.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.solver.constant.MessageConstant;
import com.solver.constant.StatusConstant;
import com.solver.dto.QuestionDTO;
import com.solver.dto.QuestionPageQueryDTO;
import com.solver.entity.Question;
import com.solver.entity.QuestionDifficulty;
import com.solver.exception.DeletionNotAllowedException;
import com.solver.mapper.FieldMapper;
import com.solver.mapper.FieldQuestionMapper;
import com.solver.mapper.QuestionDifficultyMapper;
import com.solver.mapper.QuestionMapper;
import com.solver.result.PageResult;
import com.solver.service.QuestionService;
import com.solver.vo.QuestionVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    QuestionDifficultyMapper questionDifficultyMapper;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private FieldQuestionMapper fieldQuestionMapper;


    @Override
    @Transactional//使用事务的方式（需要再启动类中开启）
    public void saveWithFlavor(QuestionDTO questionDTO) {
        Question question = new Question();
        BeanUtils.copyProperties(questionDTO,question);
        //插入一个题目
        questionMapper.insert(question);

        //插入多个题目难度
        //获取insert生成的主键值
        Long questionId = question.getId();

        //获取题目难度
        List<QuestionDifficulty> difficulties = questionDTO.getFlavors();
        if(difficulties != null && difficulties.size()>0){//先判断是否null可以防止程序报错
            difficulties.forEach(difficulty -> {difficulty.setQuestionId(questionId);});
            questionDifficultyMapper.insertBatch(difficulties);//批量插入
        }


    }

    @Override
    public PageResult questionPageQuery(QuestionPageQueryDTO questionPageQueryDTO) {
        PageHelper.startPage(questionPageQueryDTO.getPage(),questionPageQueryDTO.getPageSize());

        Page<QuestionVO> page = questionMapper.questionPageQuery(questionPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前问题能否删除？  --1. 是否起售中？
        for (Long id : ids) {
            Question question = questionMapper.getById(id);
            if(question.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前问题能否删除？  --2. 是否关联了套餐/领域
        List<Long> fieldIds = fieldQuestionMapper.getFieldIdsByQuestionIds(ids);
        if(fieldIds != null && fieldIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除问题数据
        /*for (Long id : ids) {
            questionMapper.delete(id);
            //删除问题难度数据
            questionDifficultyMapper.deleteByQuestionId(id);//不用管是否关联difficulty直接删就可以
        }*/

        //批量删除问题
        questionMapper.deleteByIds(ids);
        //根据问题id批量删除难度
        questionDifficultyMapper.deleteByQuestionIds(ids);



    }

    @Override
    public QuestionVO getQuestionById(Long id) {
        //查询问题数据
        Question question = questionMapper.getById(id);
        //根据问题id查询问题难度数据,封装为List
        List<QuestionDifficulty> difficulties = questionDifficultyMapper.getDifficutiesByQuestionId(id);
        //转化为VO类型的对象
        QuestionVO questionVO = new QuestionVO();
        BeanUtils.copyProperties(question,questionVO);
        //为VO添加难度数据
        questionVO.setFlavors(difficulties);
        return questionVO;
    }

    @Override
    public void updateWithDifficulty(QuestionDTO questionDTO) {

        Question question =new Question();
        BeanUtils.copyProperties(questionDTO,question);
        //修改问题数据
        questionMapper.update(question);
        //修改难度数据
        //1.删除原有难度数据
        questionDifficultyMapper.deleteByQuestionId(questionDTO.getId());
        //2.插入新的难度数据 需要判断DTO的difficulties是否为空
        List<QuestionDifficulty> difficulties = questionDTO.getFlavors();
        if(difficulties != null && difficulties.size()>0){
            difficulties.forEach(difficulty ->{
                difficulty.setQuestionId(questionDTO.getId());
            });
            questionDifficultyMapper.insertBatch(difficulties);
        }


    }

    @Override
    public List<QuestionVO> listWithDifficulty(Question question) {
        List<Question> questionList =questionMapper.list(question);

        List<QuestionVO> dishVOList = new ArrayList<>();

        for (Question d : questionList) {
            QuestionVO questionVO = new QuestionVO();
            BeanUtils.copyProperties(d,questionVO);

            //根据菜品id查询对应的口味
            List<QuestionDifficulty> difficulties = questionDifficultyMapper.getDifficutiesByQuestionId(d.getId());

            questionVO.setFlavors(difficulties);
            dishVOList.add(questionVO);
        }

        return dishVOList;
    }
}
